<template>
  <section id="app" class="todoapp">
    <header class="header">
      <h1>todos</h1>
      <input
        class="new-todo"
        placeholder="What needs to be done?"
        autocomplete="off"
        autofocus
        v-model="input"
        @keyup.enter="addTodo"
        >
    </header>
    <section class="main" v-show="count">
      <input id="toggle-all" class="toggle-all" v-model="allDone" type="checkbox">
      <label for="toggle-all">Mark all as complete</label>
      <ul class="todo-list">
        <li
          v-for="todo in filterTodos"
          :key="todo"
          :class="{ editing: todo === editingTodo, completed: todo.completed }"
        >
          <div class="view">
            <input class="toggle" type="checkbox" v-model="todo.completed">
            <label @dblclick="editTodo(todo)">{{ todo.text }}</label>
            <button class="destroy" @click="remove(todo)"></button>
          </div>
          <input
            class="edit"
            type="text"
            v-model="todo.text"
            v-editing-focus="todo === editingTodo"
            @keyup.enter="doneEdit(todo)"
            @blur="doneEdit(todo)"
            @keyup.esc="cancelEdit(todo)"
          >
        </li>
      </ul>
    </section>
    <footer class="footer" v-show="count">
      <span class="todo-count">
        <strong>{{ remainingCount }}</strong> {{ remainingCount > 1 ? 'items' : 'item' }} left
      </span>
      <ul class="filters">
        <li><a href="#/all">All</a></li>
        <li><a href="#/active">Active</a></li>
        <li><a href="#/completed">Completed</a></li>
      </ul>
      <button class="clear-completed" @click="removeCompleted" v-show="count > remainingCount">
        Clear completed
      </button>
    </footer>
  </section>
</template>

<script>
import { computed, onMounted, onUnmounted, ref, watchEffect } from "vue"
import useLocalStorage from "../utils/useLocalStorage.js"

const storage = useLocalStorage()
// 添加代办
const useAdd = todos => {
  const input = ref('xxx')
  const addTodo = () => {
    const text = input.value && input.value.trim()
    if (text.length === 0) return
    todos.value.unshift({
      text,
      completed: false
    })
  }
  return {
    input,
    addTodo
  }
}
// 删除待办
const useRemove = todos => {
  const remove = todo => {
    const index = todos.value.indexOf(todo)
    todos.value.splice(index, 1)
  }
  const removeCompleted = () => {
    todos.value = todos.value.filter(todo => !todo.completed)
  }
  return {
    remove,
    removeCompleted
  }
}
// 编辑待办事项
const useEdit = remove => {
  const editingTodo = ref({})
  let befareEditingText = ''
  const editTodo = todo => {
    editingTodo.value = todo
    befareEditingText = todo.text
  }
  const doneEdit = todo => {
    editingTodo.value = {}
    if (!todo.text.length) remove(todo)
  }
  const cancelEdit = todo => {
    editingTodo.value = {}
    todo.text = befareEditingText
  }
  return {
    editingTodo,
    editTodo,
    doneEdit,
    cancelEdit
  }
}
// 切换待办事项完成状态
const useFilter = todos => {
  const allDone = computed({
    get () {
      return !todos.value.filter(todo => !todo.completed).length
    },
    set (value) {
      todos.value.forEach(todo => {
        todo.completed = value
      })
    }
  })
  const filter = {
    all: list => list,
    active: list => list.filter(item => !item.completed),
    completed: list => list.filter(item => item.completed)
  }
  const type = ref('all')
  const filterTodos = computed(() => filter[type.value](todos.value))
  const remainingCount = computed(() => filter['active'](todos.value).length)
  const onHashChange = () => {
    const hash = window.location.hash.replace('#/', '')
    if (filter[hash]) {
      type.value= hash
    } else {
      type.value = 'all'
    }
  }

  onMounted(_ => {
    window.addEventListener('hashchange', onHashChange)
    onHashChange()
  })
  onUnmounted(_ => {
    window.removeEventListener(onHashChange)
  })
  return {
    allDone,
    filterTodos,
    remainingCount
  }
}

// 储存待办事项
const usetStorage = () => {
  const KEY = 'TODOKEYS'
  const todos = ref(storage.getItem(KEY) || [])
  watchEffect(() => {
    storage.setItem(KEY, todos.value)
  })
  return todos
}
export default {
  name: 'App',
  setup () {
    const todos = usetStorage()
    const { remove, removeCompleted } = useRemove(todos)
    const count = computed(() => {
      return todos.value.length
    })
    return {
      count,
      todos,
      remove,
      removeCompleted,
      ...useAdd(todos),
      ...useEdit(todos),
      ...useEdit(remove),
      ...useFilter(todos)
    }
  },
  directives: {
    editingFocus(el, binding){
      binding.value && el.focus()
    }
  }
}
</script>

<style>
</style>
